package com.letv.whatslive.mongo.dao;

import com.google.common.collect.Lists;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.Firmware;
import com.letv.whatslive.model.convert.FirmwareConvert;
import com.letv.whatslive.mongo.BaseDAO;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.WriteResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by liyulin on 2016/1/15.
 */
@Repository
public class FirmwareDAO extends BaseDAO {

    private static final Logger logger = LoggerFactory.getLogger(FirmwareDAO.class);

    protected String collectionName = "firmware";

    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }

    /**
     * 根据查询条件查询所有的固件列表
     * @param params
     * @return
     */
    public List<Firmware> getFirmwareList(Map<String, Object> params) {
        List<Firmware> firmwareList = Lists.newArrayList();
        try {
            BasicDBObject queryCondition = getQueryConditionByParams(params);
            DBCursor dbCursor = dbCollection.find(queryCondition);
            while (dbCursor.hasNext()) {
                Firmware firmware = FirmwareConvert.castDBObjectToFirmware(dbCursor.next());
                firmwareList.add(firmware);
            }
        } catch (Exception e) {
            logger.error("getFirmwareList by params error!", e);
        }
        return firmwareList;
    }


    /**
     * 根据查询条件查询所有的固件列表
     * @param params
     * @param start
     * @param limit
     * @return
     */
    public List<Firmware> getFirmwareListByParams(Map<String, Object> params, Integer start, Integer limit) {
        List<Firmware> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip).limit(limit);//按照视频类型和创建时间倒序
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                Firmware firmware = FirmwareConvert.castDBObjectToFirmware(dbObject);
                result.add(firmware);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     *根据设备Id获取固件
     * @param id
     * @return
     */
    public Firmware getFirmwareById(Long id) {
        BasicDBObject query = new BasicDBObject();
        Firmware firmware = new Firmware();
        query.put("_id", id);
        DBObject dbObject = this.dbCollection.findOne(query);
        if (dbObject == null) return null;
        try {
            firmware = FirmwareConvert.castDBObjectToFirmware(dbObject);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return firmware;
    }

    /**
     * 保存固件
     * @param firmware
     * @return
     */
    public Firmware saveFirmware(Firmware firmware) {
        try {
            firmware.setId(getAutoIncrementId());
            DBObject dbo = FirmwareConvert.castfirmwareToDBObject(firmware);
            WriteResult wr = this.dbCollection.insert(dbo);
            return firmware;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }
    public Long countFirmwareByParams(Map params) {
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = getBasicDBObjectByParams(params);
        return this.dbCollection.count(query);
    }

    /**
     * 更新固件
     * @param firmware
     */
    public void updateFirmware(Firmware firmware) {
        DBObject queryCondition = new BasicDBObject();
        queryCondition.put("_id", firmware.getId());
        BasicDBObject setValue = (BasicDBObject)FirmwareConvert.castfirmwareToDBObject(firmware);
        //剔除主键修改
        if (setValue.containsField("_id")) {
            setValue.removeField("_id");
        }
        DBObject values = new BasicDBObject("$set", setValue);
        this.dbCollection.update(queryCondition, values, false, false);
    }

    private BasicDBObject getOrderParams(Map<String, Object> orders) {
        BasicDBObject order = new BasicDBObject();
        if(null != orders &&orders.size()>0){
            for(String key : orders.keySet()){
                order.append(key, Integer.valueOf(String.valueOf(orders.get(key))));
            }
        }else{
            //默认按照id倒序排序
            order.append("_id", -1);
        }
        return order;
    }
    public List<Firmware> getFirmwareListByParams(Map<String, Object> params, Map<String, Object> orders, Integer start, Integer limit) {

        List<Firmware> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject order = getOrderParams(orders);
            BasicDBObject query = getBasicDBObjectByParams(params);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip).sort(order).limit(limit);//按createTime的值倒叙排列
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                Firmware firmware = FirmwareConvert.castDBObjectToFirmware(dbObject);
                result.add(firmware);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return result;
    }
    public long insertFirmware(Firmware firmware){
        DBObject obj = FirmwareConvert.castfirmwareToDBObject(firmware);
        return this.insert(obj);
    }

    public void deleteFirmwareByParams(Long id){
        BasicDBObject query = new BasicDBObject();
        query.put("_id", id);
        this.dbCollection.remove(query);
    }


    /**
     * 根据查询条件Map获取查询条件对象
     * @param params
     * @return
     */
    private BasicDBObject getBasicDBObjectByParams(Map params){
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {
            if (params.get("_id") != null) {
                query.put("_id", ObjectUtils.toLong(params.get("_id")));
            }
            if (params.get("model") != null) {
                query.put("model", ObjectUtils.toString(params.get("model")));
            }
            if (params.get("appVer") != null) {
                query.put("appVer", ObjectUtils.toString(params.get("appVer")));
            }
            if (params.get("sysVer") != null) {
                query.put("sysVer", ObjectUtils.toString(params.get("sysVer")));
            }
            if (params.get("fwName") != null) {
                Pattern pattern = Pattern.compile("^.*" + ObjectUtils.toString(params.get("fwName")) + ".*$", Pattern.CASE_INSENSITIVE);
                query.put("fwName", pattern);
            }
            if (params.get("pcode") != null) {
                query.put("pcode", ObjectUtils.toString(params.get("pcode")));
            }
            if (params.get("fwModel") != null) {
                query.put("fwModel", ObjectUtils.toString(params.get("fwModel")));
            }
            if (params.get("fwSystem") != null) {
                query.put("fwSystem", ObjectUtils.toString(params.get("fwSystem")));
            }
            if (params.get("fwVersion") != null) {
                query.put("fwVersion", ObjectUtils.toString(params.get("fwVersion")));
            }
            if (params.get("fwUrl") != null) {
                query.put("fwUrl", ObjectUtils.toString(params.get("fwUrl")));
            }
            if (params.get("fwMD5") != null) {
                query.put("fwMD5", ObjectUtils.toString(params.get("fwMD5")));
            }
            if (params.get("appVerInt") != null) {
                query.put("appVerInt", ObjectUtils.toInteger(params.get("appVerInt")));
            }
            if (params.get("fwVersionInt") != null) {
                query.put("fwVersionInt", ObjectUtils.toInteger(params.get("fwVersionInt")));
            }
            if (params.get("fwFlag") != null) {
                query.put("fwFlag", ObjectUtils.toInteger(params.get("fwFlag")));
            }
        }

        return query;
    }

    private BasicDBObject getQueryConditionByParams(Map<String, Object> params) {
        BasicDBObject query = new BasicDBObject();
        // 固件是否有效，0-无效，1-有效
        query.put("fwFlag", 1);
        if (params.get("model") != null) {
            query.put("model", params.get("model"));
        }
        if (params.get("sysVer") != null) {
            query.put("sysVer", params.get("sysVer"));
        }
        if (params.get("pcode") != null) {
            query.put("pcode", params.get("pcode"));
        }
        if (params.get("appVerInt") != null) {
            query.put("appVerInt", new BasicDBObject("$lte", params.get("appVerInt")));
        }
        return query;
    }

}
